package org.chen.wordwave.base.ui;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Color;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;

import org.chen.wordwave.R;

public class SourceView extends LinearLayout implements View.OnClickListener {

    private EditText input;
    private Button query;

    private Button delete;

    private final Context mContext;

    private SearchViewListener mListener;

    public void setEnable(boolean enable){
        query.setEnabled(enable);
        delete.setEnabled(enable);
    }
    public void setSearchViewListener(SearchViewListener listener) {
        mListener = listener;
    }

    public SourceView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
        LayoutInflater.from(context).inflate(R.layout.sourceview_layout, this);
        initViews();
    }

    private void initViews() {
        input = findViewById(R.id.input);
        input.setTextColor(Color.BLACK);
        delete = findViewById(R.id.delete);
        delete.setVisibility(GONE);
        /**
         * 返回按钮
         */
        query = findViewById(R.id.query);
        delete.setOnClickListener(this);
        query.setOnClickListener(this);
        input.setOnClickListener(this);
        input.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (TextUtils.isEmpty(s.toString())){
                    delete.setVisibility(INVISIBLE);
                }else{
                    delete.setVisibility(VISIBLE);
                }
            }
        });
    }

    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.input) {
        } else if (id == R.id.delete) {
            input.setText("");
            delete.setVisibility(GONE);
        } else if (id == R.id.query) {
            String query = input.getText().toString();
            mListener.onSearch(query);
        }
    }


    public interface SearchViewListener {

        void onSearch(String text);

    }
}
